package com.simdo.g768.SlideMenu;

import static com.simdo.g768.MainActivity.device;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;

import com.g768.Bean.BusinessRsp;
import com.g768.Bean.JsonObject;
import com.g768.MessageControl.MessageController;
import com.simdo.g768.Adapter.FileAdapter;
import com.simdo.g768.Bean.ErrResultInfo;
import com.simdo.g768.Bean.GnbBean;
import com.simdo.g768.Bean.ImsiBean;
import com.simdo.g768.Bean.ScanArfcnBean;
import com.simdo.g768.Bean.StepBean;
import com.simdo.g768.Dialog.CellManageDialog;
import com.simdo.g768.Dialog.CfgPlmnDialog;
import com.simdo.g768.Dialog.FreqDialog;
import com.simdo.g768.Dialog.GnbCityDialog;
import com.simdo.g768.Dialog.MqttDialog;
import com.simdo.g768.Dialog.MqttInfoDialog;
import com.simdo.g768.Dialog.ParamDialog;
import com.simdo.g768.File.FileItem;
import com.simdo.g768.File.FileProtocol;
import com.simdo.g768.File.FileUtil;
import com.simdo.g768.MainActivity;
import com.simdo.g768.Mqtt.MqttMsg;
import com.simdo.g768.R;
import com.simdo.g768.Util.AppLog;
import com.simdo.g768.Util.DateUtil;
import com.simdo.g768.Util.PrefUtil;
import com.simdo.g768.View.MyRadioGroup;
import com.simdo.g768.ZApplication;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;

@SuppressLint("ValidFragment")
public class SlideRightFragment extends Fragment implements View.OnClickListener{

    public SlideRightFragment(Context context) {
        this.mContext = context;
    }

    TextView tv_sync_model;
    Switch switch_special_model;
    TextView tv_mqtt_count;
    int mqttCount = 0;
    private ProgressDialog progressDialog;
    private final String message = "";
    private List<FileItem> mUpdateFilesList = new ArrayList<>();
    private FreqDialog mFreqDialog = null;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        if (mView == null) {
            initView(inflater, container);
        }
        // 用户配置自动布控的基站列表
        return mView;
    }

    private void initView(LayoutInflater inflater, ViewGroup container) {
        mView = inflater.inflate(R.layout.pager_right_slide, container, false);

        TextView tv_app_version = mView.findViewById(R.id.tv_app_version);
        PackageManager packageManager = mContext.getPackageManager();
        PackageInfo packageInfo;
        try {
            packageInfo = packageManager.getPackageInfo(mContext.getPackageName(), 0);
            tv_app_version.setText(MessageFormat.format("V {0}", packageInfo.versionName));
        } catch (PackageManager.NameNotFoundException e) {
            throw new RuntimeException(e);
        }

        mView.findViewById(R.id.ll_app_version).setOnClickListener(this);

        mView.findViewById(R.id.ll_nr_info).setOnClickListener(this);

        final String[] sync_mode = {PrefUtil.build().getString("sync_mode", "Air")};
        tv_sync_model = mView.findViewById(R.id.tv_sync_model);
        tv_sync_model.setText((sync_mode[0].equals("Air") || sync_mode[0].equals(mContext.getString(R.string.air))) ? mContext.getString(R.string.air) : sync_mode[0].equals("GPS") ? mContext.getString(R.string.GPS_BeiDou) : mContext.getString(R.string.BeiDou));
        mView.findViewById(R.id.ll_sync_model).setOnClickListener(this);
        mView.findViewById(R.id.ll_freq).setOnClickListener(this);
        mView.findViewById(R.id.ll_run_time).setOnClickListener(this);
        mView.findViewById(R.id.ll_cfg_plmn).setOnClickListener(this);

        tv_run_time = mView.findViewById(R.id.tv_run_time);
        oldTime = PrefUtil.build().getString("Auto_Arfcn_time", "0");
        tv_run_time.setText(oldTime);

        tv_cfg_plmn = mView.findViewById(R.id.tv_cfg_plmn);
        tv_cfg_plmn.setText(PrefUtil.build().getString("cfg_plmn_mode", getString(R.string.use_def)));

        switch_special_model = mView.findViewById(R.id.switch_special_model);
        setEnableSpecial();
        switch_special_model.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MainActivity.getInstance().enableSpecial = switch_special_model.isChecked();
            }
        });
        if (!ZApplication.getInstance().isTrace) mView.findViewById(R.id.ll_special_model).setVisibility(View.GONE);
        mView.findViewById(R.id.ll_data_out).setOnClickListener(this);
        mView.findViewById(R.id.ll_param_set).setOnClickListener(this);
        View ll_mqtt_set = mView.findViewById(R.id.ll_mqtt_set);
        ll_mqtt_set.setOnClickListener(this);
        tv_mqtt_count = mView.findViewById(R.id.tv_mqtt_count);
        tv_mqtt_count.setVisibility(View.GONE);
        ll_mqtt_set.setVisibility(View.GONE);

        mView.findViewById(R.id.tv_reboot).setOnClickListener(this);

        // 查询是否打开苹果识别， 查询结果json中，cfg_value字段值说明，0：未打开   1：打开苹果识别   2：仅苹果识别
        //MessageController.build().getFuncCfg(device.getId(), 5612);

        // 设置是否打开苹果识别，示例设置打开苹果识别，传1
        //MessageController.build().setFuncCfg(device.getId(), 5613, 1, "");
        TextView tv_connect_mode = mView.findViewById(R.id.tv_connect_mode);
        tv_connect_mode.setText(PrefUtil.build().getString("connect_mode", getString(R.string.hotspot)));
        mView.findViewById(R.id.ll_connect_mode).setOnClickListener(this);

        mView.findViewById(R.id.ll_iphone_mode).setOnClickListener(this);
        mView.findViewById(R.id.ll_lic_time).setOnClickListener(this);
        mView.findViewById(R.id.ll_ftp_cfg).setOnClickListener(this);
        mView.findViewById(R.id.ll_cell_manage).setOnClickListener(this);

        mView.findViewById(R.id.ll_min_rsrp).setOnClickListener(this);
        final TextView tv_min_rsrp = mView.findViewById(R.id.tv_min_rsrp);
        tv_min_rsrp.setText(String.valueOf(MainActivity.getInstance().showMinRsrp));

        final Switch switch_iphone_up_ring = mView.findViewById(R.id.switch_iphone_up_ring);
        switch_iphone_up_ring.setChecked(MainActivity.getInstance().isVibrate);
        switch_iphone_up_ring.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MainActivity.getInstance().isVibrate = switch_iphone_up_ring.isChecked();
                PrefUtil.build().putBoolean("is_vibrate", MainActivity.getInstance().isVibrate);
            }
        });

        final Switch switch_catch_alarm = mView.findViewById(R.id.switch_catch_alarm);
        switch_catch_alarm.setChecked(MainActivity.getInstance().isCatchAlarm);
        switch_catch_alarm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MainActivity.getInstance().isCatchAlarm = switch_catch_alarm.isChecked();
                PrefUtil.build().putBoolean("is_catch_alarm", MainActivity.getInstance().isCatchAlarm);
            }
        });
    }

    public void setEnableSpecial(){
        switch_special_model.setChecked(MainActivity.getInstance().enableSpecial);
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        MainActivity.getInstance().menu.resetDownX();
        switch (v.getId()) {
            case R.id.ll_app_version:
                break;
            case R.id.ll_nr_info:
                if (device == null) {
                    MainActivity.getInstance().showToast(getString(R.string.dev_offline));
                    return;
                }
                showInfoDialog();
                break;
            case R.id.ll_sync_model:
                cityDialog();
                break;
            case R.id.ll_freq:
                mFreqDialog = new FreqDialog(mContext, MainActivity.getInstance().freqList);
                mFreqDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialogInterface) {
                        mFreqDialog = null;
                    }
                });
                mFreqDialog.show();
                break;
            case R.id.ll_run_time:
                showAutoTimeDialog();
                break;
            case R.id.ll_cfg_plmn:
                showCfgPlmnDialog();
                break;
            case R.id.ll_data_out:
                List<ImsiBean> dataList = MainActivity.getInstance().getImsiList();
                LinkedList<ScanArfcnBean> dataList1 = MainActivity.getInstance().getFreqList();
                if ((dataList == null || dataList.size() <= 0) && (dataList1 == null || dataList1.size() <= 0)) {
                    MainActivity.getInstance().showToast(getString(R.string.trace_freq_no_data));
                    return;
                }
                createFileDialog();
                break;
            case R.id.tv_reboot:
                if (device == null) {
                    MainActivity.getInstance().showToast(getString(R.string.dev_offline));
                    return;
                }
                rebootDialog();
                break;
            case R.id.ll_param_set:
                showParamDialog();
                break;
            case R.id.ll_mqtt_set:
                showMqttDialog();
                break;
            case R.id.ll_connect_mode:
                if (device == null) {
                    MainActivity.getInstance().showToast(getString(R.string.dev_offline));
                    return;
                }
                showConnectModeDialog();
                break;
            case R.id.ll_iphone_mode:
                showSetReportUeTypeDialog();
                break;
            case R.id.ll_min_rsrp:
                showMinRsrpDialog();
                break;
            case R.id.ll_lic_time:
                showSetLicDialog();
                break;
            case R.id.ll_ftp_cfg:
                showFtpDialog();
                break;
            case R.id.ll_cell_manage:
                showCellManageDialog();
                break;
        }
    }

    public void showCellManageDialog() {
        CellManageDialog dialog = new CellManageDialog(mContext);
        dialog.show();
    }

    Dialog mFtpDialog = null;
    public void showFtpDialog() {
        if (mFtpDialog != null) return;

        if (device == null) {
            MainActivity.getInstance().showToast(getString(R.string.dev_offline));
            return;
        }

        if (device.getFtpInfo() == null) {
            MessageController.build().getFtpCfg(device.getId());
            return;
        }

        mFtpDialog = MainActivity.getInstance().createDialog(true);

        View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_ftp_cfg, null);

        final EditText ed_server_ip = view.findViewById(R.id.ed_server_ip);
        final EditText ed_port = view.findViewById(R.id.ed_port);
        final EditText ed_path = view.findViewById(R.id.ed_path);
        final EditText ed_user = view.findViewById(R.id.ed_user);
        final EditText ed_passwd = view.findViewById(R.id.ed_passwd);
        final EditText ed_gap = view.findViewById(R.id.ed_gap);
        JsonObject ftpInfo = device.getFtpInfo();
        ed_server_ip.setText(ftpInfo.optString("ftp_ipaddr", ""));
        ed_port.setText(String.valueOf(ftpInfo.optInt("ftp_port", 21)));
        ed_path.setText(ftpInfo.optString("ftp_path", ""));
        ed_user.setText(ftpInfo.optString("ftp_user", ""));
        ed_passwd.setText(ftpInfo.optString("ftp_passwd", ""));
        ed_gap.setText(String.valueOf(ftpInfo.optInt("upload_gap", 0)));

        view.findViewById(R.id.btn_ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (device == null) {
                    MainActivity.getInstance().showToast(getString(R.string.dev_offline));
                    return;
                }
                String server_ip = ed_server_ip.getText().toString();
                String port = ed_port.getText().toString();
                String path = ed_path.getText().toString();
                String user = ed_user.getText().toString();
                String passwd = ed_passwd.getText().toString();
                String gap = ed_gap.getText().toString();
                if (server_ip.isEmpty()){
                    MainActivity.getInstance().showToast(getString(R.string.ip_err));
                    return;
                }
                if (port.isEmpty()){
                    MainActivity.getInstance().showToast(getString(R.string.port_empty));
                    return;
                }
                if (user.isEmpty()){
                    MainActivity.getInstance().showToast(getString(R.string.user_empty));
                    return;
                }
                if (passwd.isEmpty()){
                    MainActivity.getInstance().showToast(getString(R.string.passwd_empty));
                    return;
                }
                if (gap.isEmpty()){
                    MainActivity.getInstance().showToast(getString(R.string.gap_empty));
                    return;
                }
                int i_port = Integer.parseInt(port);
                int i_gap = Integer.parseInt(gap);
                if (i_gap < 30 && i_gap != 0){
                    MainActivity.getInstance().showToast(getString(R.string.gap_err));
                    return;
                }
                MessageController.build().setFtpCfg(device.getId(), server_ip, i_port, path, user, passwd, i_gap);

            }
        });
        view.findViewById(R.id.back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MainActivity.getInstance().closeDialog(mFtpDialog);
                mFtpDialog = null;
            }
        });
        mFtpDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                mFtpDialog = null;
            }
        });
        MainActivity.getInstance().showDialog(mFtpDialog, view, true);
    }

    private void showSetLicDialog() {
        if (device == null) {
            MainActivity.getInstance().showToast(getString(R.string.dev_offline));
            return;
        }
        Dialog dialog = MainActivity.getInstance().createDialog(true);

        View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_cfg_lic, null);

        String date = "2099-12-31";
        String useHour = "0";
        String hour = "0";
        if (device == null) {
            MainActivity.getInstance().showToast("设备不在线，请先开启并连接设备");
            return;
        }
        String license = device.getLicense();
        RadioGroup rg_can = view.findViewById(R.id.rg_can);
        if (license.contains("EXPIRED")) {
            String[] strings = license.split("\n");

            for (String string : strings) {
                if (string.contains("EXPIRED")) {
                    if (string.contains("date")) {
                        // 新版本
                        String[] expired = string.substring(string.indexOf("(") + 1).split(",");
                        String en = expired[0].trim().split(" ")[1];
                        rg_can.check(en.equals("1") ? R.id.rb_can : R.id.rb_not_can);

                        date = expired[1].trim().split(" ")[1];
                        if (date.equals("0")) date = "2099-12-31";
                        else
                            date = date.substring(0, 4) + "-" + date.substring(4, 6) + "-" + date.substring(6);

                        int hourIndex = expired[2].trim().indexOf('/');
                        useHour = expired[2].trim().substring(5, hourIndex);
                        hour = expired[2].trim().substring(hourIndex + 1, expired[2].trim().length() - 1);
                    }

                    break;
                }
            }
        }

        final TextView tv_use = view.findViewById(R.id.tv_use);
        BigDecimal bigDecimal = BigDecimal.valueOf(Integer.parseInt(useHour) / 60d);
        double bg = bigDecimal.setScale(1, RoundingMode.HALF_UP).doubleValue();
        tv_use.setText(MessageFormat.format(getString(R.string.lic_now_use), bg, date));
        //tv_use_hour.setText(device.getLicense());
        final TextView tv_end_date = view.findViewById(R.id.tv_end_date);
        tv_end_date.setText(date);
        tv_end_date.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Calendar calendar = Calendar.getInstance();
                DatePickerDialog dialog = new DatePickerDialog(mContext, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker datePicker, int year, int monthOfYear, int dayOfMonth) {
                        monthOfYear = monthOfYear + 1;
                        tv_end_date.setText(MessageFormat.format("{0}-{1}-{2}", year, monthOfYear < 10 ? "0" + monthOfYear : monthOfYear, dayOfMonth < 10 ? "0" + dayOfMonth : dayOfMonth));
                    }
                },
                        calendar.get(Calendar.YEAR),
                        calendar.get(Calendar.MONTH),
                        calendar.get(Calendar.DAY_OF_MONTH));
                dialog.show();
            }
        });
        final EditText ed_hour = view.findViewById(R.id.ed_hour);
        ed_hour.setText(String.valueOf(Integer.parseInt(hour) / 60));
        ed_hour.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String infos = ed_hour.getText().toString();
                String result = "";

                for (int i = 0; i < infos.length(); i++) {
                    char c = infos.charAt(i);
                    if (c >= '0' && c <= '9') result += c;
                }
                while (result.startsWith("0")) {
                    result = result.substring(1);
                    if (result.length() <= 1) break;
                }
                if (result.isEmpty()) result = "0";
                else if (result.length() >= 6) result = "100000";

                if (!result.equals(infos)) ed_hour.setText(result);
                ed_hour.setSelection(result.length());
            }
        });

        view.findViewById(R.id.tv_import_lic).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Uri uri = Uri.parse("content://com.android.externalstorage.documents/document/primary:");
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                intent.setType("text/plain");
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, uri);
                }
                requestCode = 0;
                activityForResult.launch(intent);
            }
        });

        view.findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MainActivity.getInstance().closeDialog(dialog);
            }
        });
        MainActivity.getInstance().showDialog(dialog, view, true);
    }

    int requestCode = 0;
    ActivityResultLauncher<Intent> activityForResult = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
        @Override
        public void onActivityResult(ActivityResult result) {
            AppLog.I("onActivityResult result = " + result);
            if (result.getResultCode() == Activity.RESULT_OK) {
                if (result.getData() != null) {
                    AppLog.I("onActivityResult result.getData().getDataString() = " + result.getData().getDataString());
                    String dataString = result.getData().getDataString();
                    if (dataString != null && !dataString.isEmpty()) {
                        String[] split = dataString.split("%");
                        StringBuilder path = new StringBuilder(FileUtil.build().getSDPath());
                        for (int i = 1; i < split.length; i++) {
                            path.append("/");
                            path.append(split[i].substring(2));
                        }

                        //path.deleteCharAt(path.length() - 1);
                        if (requestCode == 0) { // 密匙导入

                            File file = new File(path.toString());
                            InputStreamReader inputStreamReader = null;
                            BufferedReader br = null;
                            InputStream fis = null;
                            try {
                                if (!file.exists()) {
                                    Uri uri = result.getData().getData();
                                    fis = mContext.getContentResolver().openInputStream(uri);
                                    if (fis == null){
                                        MainActivity.getInstance().showToast(getString(R.string.file_read_fail));
                                        return;
                                    }
                                }
                                if (fis == null) fis = new FileInputStream(file);
                                inputStreamReader = new InputStreamReader(fis);
                                br = new BufferedReader(inputStreamReader);
                                String line;
                                String license_key = "";
                                while (null != (line = br.readLine())) {
                                    if (!line.isEmpty()) {
                                        if (line.startsWith("license_key:")){
                                            license_key = line.substring(12).trim();
                                            break;
                                        }
                                    }
                                }
                                if (license_key.isEmpty()) {
                                    MainActivity.getInstance().showToast(getString(R.string.file_read_fail));
                                    return;
                                }
                                if (device == null) {
                                    MainActivity.getInstance().showToast(getString(R.string.dev_offline));
                                    return;
                                }
                                MessageController.build().setLicense(device.getId(), license_key);
                            } catch (Exception e) {
                                MainActivity.getInstance().showToast(getString(R.string.file_read_fail));
                            } finally {
                                if (null != fis) {
                                    try { fis.close(); } catch(Exception ignored) { }
                                }
                                if (null != br) {
                                    try { br.close(); } catch (Exception ignored) { }
                                }
                                if (null != inputStreamReader) {
                                    try { inputStreamReader.close(); } catch (Exception ignored) { }
                                }
                            }
                        }
                    }
                }
            } else if (result.getResultCode() == Activity.RESULT_CANCELED) {
                //MainActivity.getInstance().showToast("您未选择文件!");
            }
        }
    });

    private void showMinRsrpDialog() {
        final TextView tv_min_rsrp = mView.findViewById(R.id.tv_min_rsrp);

        Dialog dialog = MainActivity.getInstance().createDialog(false);

        View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_min_rsrp, null);
        final EditText ed_auto = view.findViewById(R.id.ed_auto);
        ed_auto.setText(String.valueOf(MainActivity.getInstance().showMinRsrp));
        ed_auto.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                while (s.toString().startsWith("0")) s.delete(0,1);
            }
        });
        ed_auto.setHint(Html.fromHtml("<font color=\"#b6b6b6\"><small>1 ~ 95</small></font>"));
        TextView btn_ok = view.findViewById(R.id.btn_ok);
        btn_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //按下确定键后的事件
                String newRsrp = ed_auto.getText().toString();
                if (newRsrp.isEmpty()){
                    MainActivity.getInstance().showToast(getString(R.string.not_empty));
                    return;
                }
                int minRsrp = Integer.parseInt(newRsrp);
                if (minRsrp > 95){
                    MainActivity.getInstance().showToast(getString(R.string.value_max_95));
                    return;
                }
                if (MainActivity.getInstance().showMinRsrp != minRsrp) {
                    PrefUtil.build().putInt("show_min_rsrp", minRsrp);
                    MainActivity.getInstance().showMinRsrp = minRsrp;
                    tv_min_rsrp.setText(newRsrp);
                }
                MainActivity.getInstance().showToast(mContext.getString(R.string.update_ok));
                MainActivity.getInstance().closeDialog(dialog);
            }
        });
        view.findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MainActivity.getInstance().closeDialog(dialog);
            }
        });
        MainActivity.getInstance().showDialog(dialog, view, false);
    }

    private void showSetReportUeTypeDialog() {
        if (device == null) {
            MainActivity.getInstance().showToast(getString(R.string.dev_offline));
            return;
        }
        Dialog dialog = MainActivity.getInstance().createDialog(false);

        View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_report_ue_type, null);

        // 创建一个数据集合
        List<String> dataList = new ArrayList<>();
        dataList.add(getString(R.string.close_iphone));
        dataList.add(getString(R.string.open_iphone));
        dataList.add(getString(R.string.only_iphone));

        // 创建一个适配器对象
        Spinner sp_report_ue_type = view.findViewById(R.id.sp_report_ue_type);
        ArrayAdapter<String> adapter = new ArrayAdapter<>(mContext, android.R.layout.simple_spinner_item, dataList);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        sp_report_ue_type.setAdapter(adapter);
        sp_report_ue_type.setSelection(PrefUtil.build().getInt("iphone_mode", 0), true);
        view.findViewById(R.id.btn_ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int type = sp_report_ue_type.getSelectedItemPosition();
                MainActivity.getInstance().showToast(mContext.getString(R.string.setting_ing));
                MessageController.build().setFuncCfg(device.getId(), 5613, type, "");
                MainActivity.getInstance().closeDialog(dialog);
            }
        });
        view.findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MainActivity.getInstance().closeDialog(dialog);
            }
        });
        MainActivity.getInstance().showDialog(dialog, view, false);
    }

    private void showConnectModeDialog(){
        Dialog dialog = MainActivity.getInstance().createDialog(false);
        View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_connect_mode, null);
        MyRadioGroup rb_mode = view.findViewById(R.id.rb_mode);
        TextView tv_connect_mode = mView.findViewById(R.id.tv_connect_mode);
        if (tv_connect_mode.getText().toString().equals(mContext.getString(R.string.cable))) rb_mode.check(R.id.rb_dual);
        else rb_mode.check(R.id.rb_single);

        final TextView btn_ok = view.findViewById(R.id.btn_ok);
        btn_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String connect_mode = rb_mode.getCheckedRadioButtonId() == R.id.rb_dual ? mContext.getString(R.string.cable) : mContext.getString(R.string.hotspot);
                tv_connect_mode.setText(connect_mode);
                int mode = connect_mode.equals(mContext.getString(R.string.hotspot)) ? 0 : 1;
                MessageController.build().setFuncCfg(device.getId(), 12, mode, "");
                MainActivity.getInstance().closeDialog(dialog);
            }
        });
        view.findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MainActivity.getInstance().closeDialog(dialog);
            }
        });
        MainActivity.getInstance().showDialog(dialog, view, false);
    }

    String oldTime;
    TextView tv_run_time, tv_cfg_plmn;
    private void showAutoTimeDialog(){
        Dialog dialog = MainActivity.getInstance().createDialog(false);

        View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_auto_time, null);
        final EditText ed_auto = view.findViewById(R.id.ed_auto);
        ed_auto.setText(oldTime);

        ed_auto.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String string = s.toString();
                while (string.length() > 1 && string.startsWith("0")) s.delete(0,1);
            }
        });
        ed_auto.setHint(Html.fromHtml("<font color=\"#b6b6b6\"><small>为0则不轮循</small></font>"));
        TextView btn_ok = view.findViewById(R.id.btn_ok);
        btn_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //按下确定键后的事件
                String newTime = ed_auto.getText().toString();
                if (newTime.isEmpty()){
                    MainActivity.getInstance().showToast(getString(R.string.run_time_not_null));
                    return;
                }else {
                    if (Integer.parseInt(newTime) < 20 && !newTime.equals("0")){
                        MainActivity.getInstance().showToast(getString(R.string.run_time_min));
                        return;
                    }
                }

                if (!oldTime.equals(newTime)) {
                    PrefUtil.build().putString("Auto_Arfcn_time", newTime);
                    oldTime = newTime;
                    tv_run_time.setText(oldTime);
                    MainActivity.getInstance().autoArfcnTime = Integer.parseInt(newTime);
                }
                MainActivity.getInstance().showToast(mContext.getString(R.string.update_ok));

                MainActivity.getInstance().resetAutoArfcnTime();
                hideSoftKeyBoard(view);
                MainActivity.getInstance().closeDialog(dialog);
            }
        });
        view.findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MainActivity.getInstance().closeDialog(dialog);
            }
        });
        MainActivity.getInstance().showDialog(dialog, view, false);
    }

    CfgPlmnDialog mCfgPlmnDialog;
    private void showCfgPlmnDialog() {
        mCfgPlmnDialog = new CfgPlmnDialog(mContext);
        mCfgPlmnDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                final String cfg_plmn_mode = PrefUtil.build().getString("cfg_plmn_mode", getString(R.string.use_def));
                tv_cfg_plmn.setText(cfg_plmn_mode);
                mCfgPlmnDialog = null;
            }
        });
        mCfgPlmnDialog.show();
    }

    private void hideSoftKeyBoard(View view) {
        if (view != null) {
            InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    private void showParamDialog(){
        ParamDialog dialog = new ParamDialog(mContext);
        dialog.show();
    }

    MqttInfoDialog mMqttInfoDialog;
    private void showMqttDialog(){
        if (MainActivity.getInstance().mqttConnection.getMqttBean().getHost().isEmpty()){
            MqttDialog dialog = new MqttDialog(mContext);
            dialog.show();
        }else {
            mMqttInfoDialog = new MqttInfoDialog(mContext);
            mMqttInfoDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialogInterface) {
                    mMqttInfoDialog = null;
                }
            });
            clearCount();
            mMqttInfoDialog.show();
        }
    }

    public void mqttNotifyDataSetChanged(MqttMsg mqttMsg){
        if (mMqttInfoDialog != null) {
            mMqttInfoDialog.notifyDataSetChanged(mqttMsg);
            if (!mMqttInfoDialog.isShowing()) {
                setMqttCount(++mqttCount);
                if (tv_mqtt_count.getVisibility() == View.GONE) tv_mqtt_count.setVisibility(View.VISIBLE);
            }
        }else if (mqttMsg == null) {
        }
        else if (MainActivity.getInstance().mqttConnection.getMqttBean().isShow()) showMqttDialog();
        else {
            ++mqttCount;
            if (tv_mqtt_count == null) return;
            setMqttCount(mqttCount);
            if (tv_mqtt_count.getVisibility() == View.GONE) tv_mqtt_count.setVisibility(View.VISIBLE);
        }
    }

    public void setMqttCount(int count){
        tv_mqtt_count.setText(MessageFormat.format("+{0}", count));
    }

    public void clearCount(){
        mqttCount = 0;
        if (tv_mqtt_count == null) return;
        setMqttCount(0);
        tv_mqtt_count.setVisibility(View.GONE);
    }

    GnbCityDialog mGnbCityDialog;
    private void cityDialog() {
        mGnbCityDialog = new GnbCityDialog(mContext);
        mGnbCityDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                final String sync_mode = PrefUtil.build().getString("sync_mode", "Air");
                tv_sync_model.setText(sync_mode.equals("Air") ? mContext.getString(R.string.air) : sync_mode.equals("GPS") ? mContext.getString(R.string.GPS_BeiDou) : mContext.getString(R.string.BeiDou));
                mGnbCityDialog = null;
            }
        });
        mGnbCityDialog.show();
    }
    private void rebootDialog() {
        Dialog dialog = MainActivity.getInstance().createDialog(false);
        View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_confirm, null);
        TextView tv_title = view.findViewById(R.id.tv_title);
        tv_title.setText(R.string.reboot);
        TextView tv_msg = view.findViewById(R.id.tv_msg);
        tv_msg.setText(R.string.reboot_tip);
        final TextView btn_ok = view.findViewById(R.id.btn_ok);
        btn_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int workState = device.getWorkState();
                if (workState != GnbBean.State.REBOOT && workState != GnbBean.State.NONE) {
                    MainActivity.getInstance().updateSteps(StepBean.State.success, getString(R.string.rebooting));
                    device.setWorkState(GnbBean.State.REBOOT);
                    MessageController.build().rebootDev(device.getId());
                }

                MainActivity.getInstance().closeDialog(dialog);
            }
        });
        view.findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MainActivity.getInstance().closeDialog(dialog);
            }
        });
        MainActivity.getInstance().showDialog(dialog, view, false);
    }

    private void showInfoDialog() {
        AppLog.D("SlideRightFragment showInfoDialog()");

        Dialog dialog = MainActivity.getInstance().createDialog(true);

        View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_info, null);

        TextView tv_hard_version = view.findViewById(R.id.tv_hard_version);
        tv_hard_version.setText(device.getHwVer());
        TextView tv_login_version = view.findViewById(R.id.tv_login_version);
        tv_login_version.setText(device.getFpgaVer());

        TextView tv_soft_version = view.findViewById(R.id.tv_soft_version);
        tv_soft_version.setText(device.getSoftVer());

        view.findViewById(R.id.back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MainActivity.getInstance().closeDialog(dialog);
            }
        });

        view.findViewById(R.id.get_bs_log).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (device == null || device.getWorkState() != GnbBean.State.IDLE) {
                    MainActivity.getInstance().showToast(getString(R.string.dev_busy_tip));
                    return;
                }
                showGetBsLogDialog();
            }
        });

        view.findViewById(R.id.get_op_log).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (device == null || device.getWorkState() != GnbBean.State.IDLE) {
                    MainActivity.getInstance().showToast(getString(R.string.dev_busy_tip));
                    return;
                }
                showGetOpLogDialog();
            }
        });

        view.findViewById(R.id.upgrade).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showUpgradeDialog();
            }
        });

        MainActivity.getInstance().showDialog(dialog, view, true);
    }
    private void showGetBsLogDialog() {
        AppLog.D("SlideRightFragment showGetBsLogDialog()");
        Dialog dialog = MainActivity.getInstance().createDialog(false);

        View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_create_log, null);
        final EditText ed_file_name = view.findViewById(R.id.ed_file_name);
        TextView btn_ok = view.findViewById(R.id.btn_ok);
        btn_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String gnbLogName = "";
                String time = DateUtil.getFormatCurrentTime("yyyyMMdd_HHmm");
                String name = ed_file_name.getEditableText().toString().trim();
                byte[] bytes = name.getBytes();
                if (bytes.length > 35) { // 64 - 15 = 49
                    MainActivity.getInstance().showToast(getString(R.string.log_name_more));
                    return;
                }
                gnbLogName = name + "_" + time;
                gnbLogName = gnbLogName.replaceAll(" ", "");

                if (device == null) {
                    MainActivity.getInstance().showToast(getString(R.string.now_dev_offline));
                    return;
                }
                String deviceId = device.getId();
                device.setWorkState(GnbBean.State.GET_LOG);
                MessageController.build().getDevLog(deviceId, 3, 100, FileProtocol.FILE_BS_LOG, gnbLogName);

                MainActivity.getInstance().updateSteps(StepBean.State.success, getString(R.string.dev_reading_log));

                MainActivity.getInstance().closeDialog(dialog);
            }
        });
        view.findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MainActivity.getInstance().closeDialog(dialog);
            }
        });
        MainActivity.getInstance().showDialog(dialog, view, false);
    }

    private void showGetOpLogDialog() {
        AppLog.D("SlideRightFragment showGetOpLogDialog()");
        Dialog dialog = MainActivity.getInstance().createDialog(false);

        View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_create_oplog, null);
        final EditText ed_file_name = view.findViewById(R.id.ed_file_name);
        view.findViewById(R.id.btn_ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String gnbLogName;
                String time = DateUtil.getFormatCurrentTime("yyyyMMdd_HHmmss");
                String name = ed_file_name.getEditableText().toString().trim();
                byte[] bytes = name.getBytes();
                if (bytes.length > 35) { // 64 - 15 = 49
                    MainActivity.getInstance().showToast(getString(R.string.log_name_more));
                    return;
                }

                if (device == null) {
                    MainActivity.getInstance().showToast(getString(R.string.now_dev_offline));
                    return;
                }
                gnbLogName = name + "_" + time;
                gnbLogName = gnbLogName.replaceAll(" ", "");

                String deviceId = device.getId();
                device.setWorkState(GnbBean.State.GET_LOG);

                MainActivity.getInstance().updateSteps(StepBean.State.success, getString(R.string.dev_reading_op_log));

                MessageController.build().getOpLog(deviceId, FileProtocol.FILE_OP_LOG, gnbLogName, 0, 0);

                MainActivity.getInstance().closeDialog(dialog);
            }
        });
        view.findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MainActivity.getInstance().closeDialog(dialog);
            }
        });
        MainActivity.getInstance().showDialog(dialog, view, false);
    }

    private void showUpgradeDialog() {
        AppLog.D("SlideRightFragment showUpgradeDialog()");
        if (device == null){
            MainActivity.getInstance().showToast(getString(R.string.dev_busy_please_wait));
            return;
        }
        if (device.getWorkState() != GnbBean.State.IDLE) {
            MainActivity.getInstance().showToast(getString(R.string.dev_busy_please_wait));
            return;
        }
        double vol = device.getHeartbeat().getDev_info().getVoltage().get(1) / 1000.0;
        if (vol < 1){
        }else if (vol < 16.6) {
            //MainActivity.getInstance().showRemindDialog(getString(R.string.vol_min_title), getString(R.string.vol_min_tip));
            //return;
        }
        Dialog dialog = MainActivity.getInstance().createDialog(true);
        mUpdateFilesList.clear();
        mUpdateFilesList = FileUtil.build().getUpdateFileList();
        View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_updata_file, null);
        // 附近频点
        ListView fileListView = view.findViewById(R.id.file_list);
        FileAdapter fileAdapter = new FileAdapter(mContext, mUpdateFilesList);
        fileListView.setAdapter(fileAdapter);

        fileListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> list, View v, int pos, long id) {
                new AlertDialog.Builder(mContext)
                        .setTitle("升级提示")
                        .setMessage("确定要升级设备版本至" + mUpdateFilesList.get(pos).getFileName() + "吗？")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                if (device == null) {
                                    MainActivity.getInstance().showToast("设备不在线，请先开启并连接设备");
                                    return;
                                }
                                MainActivity.getInstance().closeDialog(dialog);
                                device.setWorkState(GnbBean.State.UPDATE);
                                MainActivity.getInstance().updateSteps(StepBean.State.success, "开始升级基带系统");

                                MessageController.build().upgradeDev(device.getId(), new File(mUpdateFilesList.get(pos).getPath()));
                            }
                        })
                        .setNegativeButton("取消", null)
                        .show();
            }
        });
        view.findViewById(R.id.back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MainActivity.getInstance().closeDialog(dialog);
            }
        });
        MainActivity.getInstance().showDialog(dialog, view, true);
    }

    private void createFileDialog() {
        final Dialog mDialog = new Dialog(mContext, R.style.style_dialog);
        mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        mDialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
        mDialog.setCancelable(true);   // 返回键不消失
        View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_create_file, null);
        final EditText mEtFileName = view.findViewById(R.id.ed_file_name);
        mEtFileName.setText("data");
        TextView btn_ok = view.findViewById(R.id.btn_ok);
        TextView btn_cancel = view.findViewById(R.id.btn_cancel);
        btn_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = mEtFileName.getText().toString().trim();
                if (name.isEmpty()){
                    MainActivity.getInstance().showToast(getString(R.string.input_file_name));
                }else {
                    saveDataList(name, true);
                    mDialog.dismiss();
                }
            }
        });
        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
            }
        });
        mDialog.setContentView(view);
        mDialog.show();
    }

    public void saveDataList(String fileName, boolean isShow) {
        String stime = DateUtil.getFormatCurrentTime("yyyyMMdd_HHmmss");
        if (!fileName.isEmpty()) {
            fileName = fileName + "_" + stime;
        } else {
            fileName = "B97621_" + stime;
        }
        String filePath;
        int size;
        String count;

        StringBuilder sb = new StringBuilder();

        List<ScanArfcnBean> scanArfcnBeanList = MainActivity.getInstance().getFreqList();
        String resultDir = "/";
        if (!scanArfcnBeanList.isEmpty()) {
            resultDir = "扫频结果";
            filePath = FileUtil.build().createOrAppendFile(getString(R.string.filename) + fileName, FileProtocol.DIR_Scan_RESULT, fileName, 0);
            AppLog.D("save scan data: filePath = " + filePath);
            size = scanArfcnBeanList.size();
            sb.append("\r\n");
            sb.append(getString(R.string.file_path)).append(filePath);
            sb.append("\r\n");
            count = getString(R.string.scan_count) + size;
            sb.append(count);
            sb.append("\r\n");
            for (int i = 0; i < size; i++) {
                sb.append(scanArfcnBeanList.get(i).getTac());
                sb.append("\t");
                sb.append(scanArfcnBeanList.get(i).getEci());
                sb.append("\t");
                sb.append(scanArfcnBeanList.get(i).getPlmn());
                sb.append("\t");
                sb.append(scanArfcnBeanList.get(i).getDl_arfcn());
                sb.append("\t");
                sb.append(scanArfcnBeanList.get(i).getPci());
                sb.append("\t");
                sb.append(scanArfcnBeanList.get(i).getRsrp());
                sb.append("\t");
                sb.append(scanArfcnBeanList.get(i).getBandwidth());
                sb.append("\n");
            }
            FileUtil.build().appendFile(filePath, sb.toString());
        }

        List<ImsiBean> mImsiList = MainActivity.getInstance().getImsiList();
        if (!mImsiList.isEmpty()) {
            resultDir += "、定位侦码";
            filePath = FileUtil.build().createOrAppendFile(getString(R.string.filename) + fileName, FileProtocol.DIR_TRACE_IMSI, fileName, 0);
            AppLog.D("save imsi data: filePath = " + filePath);
            sb.delete(0, sb.length());
            size = mImsiList.size();
            sb.append("\r\n");
            sb.append(getString(R.string.file_path)).append(filePath);
            sb.append("\r\n");
            count = getString(R.string.catch_trace_count) + size;
            sb.append(count);
            sb.append("\r\n");
            for (int i = 0; i < size; i++) {
                sb.append(DateUtil.formateTimeHMS(mImsiList.get(i).getLatestTime()));
                sb.append("\t\t");
                sb.append(mImsiList.get(i).getImsi());
                sb.append("\t\t");
                sb.append(mImsiList.get(i).getArfcn());
                sb.append("\t\t");
                sb.append(mImsiList.get(i).getPci());
                sb.append("\t\t");
                sb.append(mImsiList.get(i).getRsrp());
                sb.append("\r\n");
            }
            FileUtil.build().appendFile(filePath, sb.toString());
        }

        if (isShow) MainActivity.getInstance().showRemindDialog(getString(R.string.out_result), getString(R.string.data_out_success_start) + FileProtocol.DIR_BASE + resultDir + getString(R.string.data_out_success_end));
    }

    public void onSetRebootRsp(String id, BusinessRsp rsp) {
        if (rsp.getResult() == 0) {
            MainActivity.getInstance().setDevState(-1, getString(R.string.not_ready));
            MainActivity.getInstance().initProgress();
            MainActivity.getInstance().showRemindDialog("重启提示", "设备正在重启！");
        }
        else MainActivity.getInstance().showToast(ErrResultInfo.getInfoByErrCode(rsp.getResult()));
    }

    public void onUpgradeRsp(String id, BusinessRsp rsp) {
        if (rsp.getResult() == 0){
            // rsp.getResult() == 0的情况下，分4步回调（step：0、1、2、3）
            // 0：读取升级文件，准备向设备传输升级文件
            // 1：开始向设备传输升级文件取，以及传输进度
            // 2：传输升级文件完成，并通知设备升级
            // 3：rsp.getResult() == 0，rsp.getJson()为空，表示升级完成，设备即将重启
            if (rsp.getJson() == null){
                MainActivity.getInstance().setDevState(-1, getString(R.string.not_ready));
                MainActivity.getInstance().initProgress();
                MainActivity.getInstance().updateSteps(StepBean.State.success, "升级成功，设备正在重启！");
                MainActivity.getInstance().showRemindDialog("升级提示", "升级成功，设备正在重启！");
                return;
            }
            switch (rsp.getJson().getInt("step")){
                case 0:
                    freshProgress(0, "升级提示", "正在读取升级文件");
                    break;
                case 1:
                    freshProgress(1, "升级提示", "正在传输升级文件，进度：" + rsp.getJson().getLong("progress") + "%");
                    break;
                case 2:
                    freshProgress(2, "升级提示", "传输升级文件完成，正在通知设备升级");
                    break;
            }
        }else freshProgress(3, "升级提示", "升级失败，" + ErrResultInfo.getInfoByErrCode(rsp.getResult()));
    }

    public void onGetLogRsp(String id, BusinessRsp rsp) {
        if (rsp.getResult() == 0){
            // rsp.getResult() == 0的情况下，分3步回调（step：0、1、2）
            // 0：通知设备打包日志
            // 1：设备打包好日志，开始从设备提取日志，以及上报提取进度
            // 2：提取日志完成
            switch (rsp.getJson().getInt("step")){
                case 0:
                    freshProgress(0, "提取日志", "正在通知设备打包日志");
                    break;
                case 1:
                    freshProgress(1, "提取日志", "正在提取日志，进度：" + rsp.getJson().getLong("progress") + "%");
                    break;
                case 2:
                    freshProgress(2, "提取日志", "提取日志成功，路径：" + FileProtocol.FILE_BS_LOG);
                    break;
            }
        }else freshProgress(3, "提取日志", "提取日志失败，" + ErrResultInfo.getInfoByErrCode(rsp.getResult()));
    }

    public void onGetOpLogRsp(String id, BusinessRsp rsp) {
        if (rsp.getResult() == 0){
            // rsp.getResult() == 0的情况下，分3步回调（step：0、1、2）
            // 0：通知设备打包日志
            // 1：设备打包好日志，开始从设备提取日志，以及上报提取进度
            // 2：提取日志完成
            switch (rsp.getJson().getInt("step")){
                case 0:
                    freshProgress(0, "提取黑匣子", "正在通知设备打包黑匣子");
                    break;
                case 1:
                    freshProgress(1, "提取黑匣子", "正在提取黑匣子，进度：" + rsp.getJson().getLong("progress") + "%");
                    break;
                case 2:
                    freshProgress(2, "提取黑匣子", "提取黑匣子成功，路径：" + FileProtocol.FILE_OP_LOG);
                    break;
            }
        }else freshProgress(3, "提取黑匣子", "提取黑匣子失败，" + ErrResultInfo.getInfoByErrCode(rsp.getResult()));
    }

    public void onGetFileRsp(String id, BusinessRsp rsp) {
        if (rsp.getResult() == 0){
            // rsp.getResult() == 0的情况下，分3步回调（step：0、1、2）
            // 0：通知设备打包日志
            // 1：设备打包好日志，开始从设备提取日志，以及上报提取进度
            // 2：提取日志完成
            switch (rsp.getJson().getInt("step")){
                case 0:
                    freshProgress(0, "提取文件", "正在通知设备打包文件");
                    break;
                case 1:
                    freshProgress(1, "提取文件", "正在提取文件，进度：" + rsp.getJson().getLong("progress") + "%");
                    break;
                case 2:
                    freshProgress(2, "提取文件", "提取文件成功，路径：" + FileProtocol.DIR_Scan);
                    break;
            }
        }else freshProgress(3, "提取文件", "提取文件失败，" + ErrResultInfo.getInfoByErrCode(rsp.getResult()));
    }

    private void freshProgress(int step, String title, String msg){
        switch (step){
            case 0:
                if (progressDialog != null) {
                    progressDialog.dismiss();
                    progressDialog = null;
                }
                progressDialog = new ProgressDialog(mContext, R.style.ThemeProgressDialogStyle);
                progressDialog.setCanceledOnTouchOutside(false);
                progressDialog.setCancelable(false);
                progressDialog.setTitle(title);
                progressDialog.setMessage(msg);
                progressDialog.show();
                break;
            case 1:
                MainActivity.getInstance().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        progressDialog.setMessage(msg);
                    }
                });
                break;
            case 2:
                MainActivity.getInstance().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (progressDialog != null) {
                            progressDialog.dismiss();
                            progressDialog = null;
                        }
                        if (device != null) device.setWorkState(GnbBean.State.IDLE);
                        MainActivity.getInstance().showRemindDialog(title, msg);
                    }
                });
                break;
            case 3:
                if (progressDialog != null) {
                    progressDialog.dismiss();
                    progressDialog = null;
                }
                if (device != null) device.setWorkState(GnbBean.State.IDLE);
                MainActivity.getInstance().showRemindDialog(title, msg);
                break;
        }
    }

    public void setDeviceDis(String id) {
        if (device != null && device.getWorkState() != GnbBean.State.NONE) {
            if (progressDialog != null) {
                progressDialog.dismiss();
                progressDialog = null;
                if (message.equals(getString(R.string.copying)))
                    MainActivity.getInstance().showToast(getString(R.string.update_dev_dis_tip));
            }
        }
    }

    public void onFreqScanRsp(String id, JsonObject rsp) {
        if (mFreqDialog != null) mFreqDialog.onFreqScanRsp(id, rsp);
    }

    private View mView;

    private final Context mContext;

    public void onStartTdMeasure(String id, JsonObject rsp) {
        if (mGnbCityDialog != null) mGnbCityDialog.onStartTdMeasure(id, rsp);
    }
}
